import re, time
import requests
# pip install PyExecJS
import execjs
from django_redis import get_redis_connection
from lxml import etree

headers = {}
# 获取微信的ua_id
def get_ua_id(UserAgent):
    url = "https://mp.weixin.qq.com/"
    headers = {
        "authority": "mp.weixin.qq.com",
        "method": "GET",
        "path": "/",
        "scheme": "https",
        'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        'accept-encoding': "gzip, deflate, br",
        'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
        "cache-control": "max-age=0",
        "upgrade-insecure-requests": "1",
        'user-agent': UserAgent,
    }
    resp = requests.get(url=url, headers=headers)
    set_cookie = re.findall("ua_id=(.*?);", str(resp.headers["set-cookie"]))
    if len(set_cookie) > 0:
        return str(set_cookie[0])
    else:
        return None

def get_cookies(UserAgent):
    cookie_item = dict()
    JS = execjs.compile('''function getParams(c) {
           return (c || "") + Math.round(2147483647 * (Math.random() || .5)) * + new Date % 1E10  // 获取10位unix时间戳
        }''')
    pgv_pvi = JS.call('getParams')
    pgv_si = JS.call('getParams', "s")
    ua_id = str(get_ua_id(UserAgent))
    if not ua_id:
        return None
    # "/cgi-bin/home?t=home/index&amp;lang=zh_CN&amp;token=964210192"
    cookie = "ua_id={uaid}; pgv_pvi={pvi}; pgv_si={si};".format(uaid=ua_id, pvi=pgv_pvi, si=pgv_si)
    url = "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin"
    # 获取uuid
    headers = {
        'authority': "mp.weixin.qq.com",
        'method': "POST",
        'path': "/cgi-bin/bizlogin?action=startlogin",
        'scheme': "https",
        'accept': "*/*",
        'accept-encoding': "gzip, deflate, br",
        'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
        'content-length': "99",
        'content-type': "application/x-www-form-urlencoded; charset=UTF-8",
        'cookie': cookie,
        'origin': "https://mp.weixin.qq.com",
        'referer': "https://mp.weixin.qq.com/",
        'user-agent': UserAgent,
        'x-requested-with': "XMLHttpRequest",
    }

    unixs = int(time.time() * 100000)
    data = {
        "userlang": "zh_CN",
        "redirect_url": "",
        "login_type": "3",
        "sessionid": unixs,
        "token": "",
        "lang": "zh_CN",
        "f": "json",
        "ajax": "1"
    }
    resp = requests.post(url=url, headers=headers, data=data)
    set_cookie = re.findall("uuid=(.*?);", str(resp.headers["set-cookie"]))
    if len(set_cookie) > 0:
        cookie_item['pgv_pvi'] = pgv_pvi
        cookie_item['pgv_si'] = pgv_si
        cookie_item['ua_id'] = ua_id
        cookie_item['uuid'] = set_cookie[0]
        return cookie_item
    else:
        return None

# 格式化cookies
def format_cookies(strs):
    return_list = []
    re_data = re.findall("(\w+)=([^;]+)", strs)
    for i in re_data:
        if str(i[0]).lower() != 'path' and str(i[0]).lower() != 'expires':
            temp_str = "=".join(i) + ";"
            return_list.append(temp_str)
    return " ".join(return_list)

# 字典转换成cookies
def dict_to_cookie(**dict_tmp):
    lists = []
    for k, v in dict_tmp.items():
        temp = str(k) + "=" + str(v) + ";"
        lists.append(temp)
    return ''.join(lists)
# 爬取用户信息
def parse_info(user_agent,cookies,token):
    url = "https://mp.weixin.qq.com/cgi-bin/settingpage"
    querystring = {"t": "setting/index", "action": "index", "token": token, "lang": "zh_CN"}
    payload = ""
    headers = {
        'authority': "mp.weixin.qq.com",
        'method': "GET",
        'path': "/cgi-bin/settingpage?t=setting/index&action=index&token={}&lang=zh_CN".format(token),
        'scheme': "https",
        'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        'accept-encoding': "gzip, deflate, br",
        'accept-language': "zh,en;q=0.9,zh-CN;q=0.8",
        'cookie': str(cookies),
        'upgrade-insecure-requests': "1",
        'user-agent': user_agent,
    }
    response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
    HTML = etree.HTML(response.text)
    item = dict()
    item['logo'] = ''.join(HTML.xpath('//div[@class="weui-desktop-account__info"]/a/img/@src')).strip()
    item['user_name'] = ''.join(HTML.xpath('//div[@id="settingArea"]//ul/li[1]//span/text()')).strip()
    item['wechat_code'] = ''.join(HTML.xpath('//div[@id="settingArea"]//ul/li[2]//span/text()')).strip()
    item['user_type'] = ''.join(HTML.xpath('//div[@id="settingArea"]//ul/li[4]//div[@class="weui-desktop-setting__item__info"]/text()')).strip()
    item['introduce'] = ''.join(HTML.xpath('//div[@id="settingArea"]//ul/li[5]//div[@class="weui-desktop-setting__item__info"]/text()')).strip()
    item['authentication_status'] = ''.join(HTML.xpath('//div[@id="settingArea"]//ul/li[6]//div[@class="weui-desktop-setting__item__info"]/span/text()')).strip()
    item['address'] = ''.join(HTML.xpath('//div[@id="settingArea"]//ul/li[7]//div[@class="weui-desktop-setting__item__info"]//text()')).strip()
    return item
